package cn.huaqingcheng.tianshu.application.job;

import cn.huaqingcheng.tianshu.common.core.HttpTool;
import cn.huaqingcheng.tianshu.common.core.StrTool;
import cn.huaqingcheng.tianshu.core.start.model.Site;
import cn.huaqingcheng.tianshu.core.start.repository.SiteRepository;
import cn.huaqingcheng.tianshu.core.sys.param.SysFileUploadParam;
import cn.huaqingcheng.tianshu.core.sys.param.SysFileUploadResponse;
import cn.huaqingcheng.tianshu.core.sys.service.SysFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.security.PermitAll;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

/**
 * DataMigrationJob
 */
@Slf4j
@Profile("dev")
@RestController
@RequiredArgsConstructor
@RequestMapping("/data-migration")
public class DataMigrationJob {

    private final SiteRepository siteRepository;

    private final SysFileService fileService;


    /**
     * 迁移站点图标
     */
    @PermitAll
    @PutMapping("/site-icon")
    public void 迁移图标() {
        List<Site> sites = siteRepository.selectListByOldIcons();
        for (Site site : sites) {
            Thread.ofVirtual()
                    .name("图标迁移")
                    .start(() -> 迁移(site));
        }
    }

    private void 迁移(Site site) {
        try (InputStream is = HttpTool.download(URI.create(site.getIcon()))) {
            SysFileUploadParam param = new SysFileUploadParam()
                    .setAccountId(site.getAccountId())
                    .setOriginalName(site.getIcon());
            SysFileUploadResponse response = fileService.upload(is, param);
            site.setIcon(response.getUri().toString());

            siteRepository.update(site);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (IllegalStateException e) {
            log.warn("无法处理 {} 错误 {}", site.getIcon(), e.getLocalizedMessage());

            site.setIcon(StrTool.EMPTY);
            siteRepository.update(site);
        }
    }

}
